package org.xiaoai.cp;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 消费数据
 * @author book
 *
 */
public class Consumer<T> implements Runnable {

	/**
	 * 存放数据的队列
	 */
	private BlockingQueue<T> queue;
	/**
	 * 控制线程
	 */
    private volatile boolean  isRunning = true;
    
    
    /**
     * 线程随机休息时间
     */
    private static final int DEFAULT_RANGE_FOR_SLEEP = 1000;
	
    
	public Consumer(BlockingQueue<T> queue) {
		this.queue = queue;
	}

	@Override
	public void run() {
		while(isRunning){
		 System.out.println("消费数据开始.............");
		 try {
			T data = queue.poll(2, TimeUnit.SECONDS);
			if(data != null){
			   System.out.println("消费了数据"+data);
			   Thread.sleep(DEFAULT_RANGE_FOR_SLEEP);
			}else{
				isRunning = false;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			Thread.currentThread().interrupt();
		}finally{
			System.out.println("消费数据结束...........");
		}	
			
		}
	}
	
	public void stop(){
		isRunning = false;
	}

}
